package com.zjq.authoritysystem.config.security.sevice;

import com.zjq.authoritysystem.entity.Permission;
import com.zjq.authoritysystem.entity.User;
import com.zjq.authoritysystem.service.PermissionService;
import com.zjq.authoritysystem.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Kimiaaaaa
 * @className CommonUserDetailsService
 * @Description 用户认证处理器类
 * @date 2023-09-19 15:01
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }

        // 查询当前登录用户拥有的权限列表
        List<Permission> permissionList = permissionService.findPermissionsByUserId(user.getId());
        // 获取对应的权限编码
        List<String> codeList = permissionList.stream()
                .filter(Objects::nonNull)  // 过滤空元素(permission)数据
                .map(permission -> permission.getCode()) // 获取权限编码
                .filter(Objects::nonNull) // 过滤空权限编码(permission.code)数据
                .collect(Collectors.toList()); // 将所有非空权限编码收集到一个列表中
        // 将获取的权限编码转换成数组
        String[] codes = codeList.toArray(new String[codeList.size()]);

        // 设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(codes);
        user.setAuthorities(authorityList);

        // 设置该用户所拥有的菜单信息
        user.setPermissionList(permissionList);

        return user;
    }


}
